package com.meego.common.oembed;

import java.util.HashMap;

import org.apache.http.client.HttpClient;

public class OembedBuilder {
	private final Oembed oembed;
	
	public OembedBuilder(final HttpClient httpClient) {
		this.oembed = new Oembed(httpClient);
	}

	public OembedBuilder withAutodiscovery(boolean autodiscovery) {
		oembed.setAutodiscovery(autodiscovery);
		return this;
	}

	public OembedBuilder withBaseUri(String baseUri) {
		oembed.setBaseUri(baseUri);
		return this;
	}

	public OembedBuilder withCacheName(String cacheName) {
		oembed.setCacheName(cacheName);
		return this;
	}

	public OembedBuilder withIgnoreFailedUrlsForSeconds(Long ignoreFailedUrlsForSeconds) {
		oembed.setIgnoreFailedUrlsForSeconds(ignoreFailedUrlsForSeconds);
		return this;
	}

	public OembedBuilder withConsumer(String consumer) {
		oembed.setConsumer(consumer);
		return this;
	}
	
	/**
	 * Adds the given providers to the map if the format is supported
	 * @param provider
	 * @return
	 */
	public OembedBuilder withProviders(final OembedProvider... providers) {
		if(providers != null) {
			if(oembed.getProvider() == null)
				oembed.setProvider(new HashMap<String, OembedProvider>());
			for(OembedProvider provider : providers) {
				if(!this.oembed.getParser().containsKey(provider.getFormat().toLowerCase()))
					throw new RuntimeException(String.format("Invalid format %s", provider.getFormat()));
				oembed.getProvider().put(provider.getName(), provider);
			}
		}
		return this;
	}
	
	public OembedBuilder withHandlers(final OembedResponseHandler... handlers) {
		if(handlers != null) {
			if(oembed.getHandler() == null)
				oembed.setHandler(new HashMap<String, OembedResponseHandler>());
			for(OembedResponseHandler handler : handlers) {
				this.oembed.getHandler().put(handler.getFor(), handler);
			}
		}
		return this;
	}

	public Oembed build() {
		return oembed;
	}
}